﻿#ifndef OBJECTTRACE_H
#define OBJECTTRACE_H

#include <signalslot.h>

//对象追踪类，能够在被析构时发出Destoried信号
//使用对象指针，能够在对象被析构后检测出对象失效

template  <typename T>
class ObjectPointer;

class REFLECTX_EXPORT ObjectTrace
{
public:
	ObjectTrace();
    virtual ~ObjectTrace();

	Signal<> Destoried;

	std::shared_ptr<ObjectTrace*> selfPointer;

	template  <typename T>
	friend class ObjectPointer;
};

template  <typename T>
class ObjectPointer {
public:
	ObjectPointer(T* target = NULL) {
		targetPointer = target->selfPointer;
	}
	ObjectPointer(const ObjectPointer<T>& other) {
		targetPointer = other.targetPointer;
	}

	T* operator->()
	{
		auto s = targetPointer.lock();
		if (s) {
			return dynamic_cast<T*>(*s);
		}
		return NULL;
	}

	T* get() {
		auto s = targetPointer.lock();
		if (s) {
			return dynamic_cast<T*>(*s);
		}
		return (NULL);
	}

	operator T*() {
		auto s = targetPointer.lock();
		if (s) {
			return dynamic_cast<T*>(*s);
		}
		return (NULL);
	}

	std::weak_ptr<ObjectTrace*> targetPointer;
};

#endif // OBJECTTRACE_H
